package com.sphd.restaurantsystem.utils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.protocol.HTTP;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Hu on 2016/11/22.
 */

public class UpLoadRequest extends Request {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    HttpEntity httpEntity = builder.build();
    Map<String, File> fileUpload;
    Map<String, String> stringUpload;
    private Response.Listener mListener;

    public UpLoadRequest(int method, String url, Response.ErrorListener listener) {
        super(method, url, listener);
        buileEntity();
    }

    public UpLoadRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener
            , Map<String, File> fileUpload, Map<String, String> params) {
        super(method, url, errorListener);
        this.mListener = listener;
        this.fileUpload = fileUpload;
        this.stringUpload = params;
        buileEntity();
    }


    private void buileEntity() {

        for (Map.Entry<String, File> entry : fileUpload.entrySet()) {

            builder.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
        }

        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        // Iterate the stringUploads

        for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
            try {
                builder.addPart(((String) entry.getKey()),
                        new StringBody((String) entry.getValue(), contentType));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(Object response) {
        mListener.onResponse(response);
    }


    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();

        if (headers == null || headers.equals(Collections.emptyMap())) {
            headers = new HashMap<String, String>();
        }
        return headers;
    }

    @Override
    public String getBodyContentType() {
        return httpEntity.getContentType().getValue();
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            httpEntity.writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }
}
